/*
 * @Description: 列表
 * @Author: Zzt
 * @Date: 2022-11-27 16:43:08
 * @LastEditTime: 2023-01-11 21:24:31
 */

import { IPageQuery } from '@/interfaces/global';
import { Button, Space, Table } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { ColumnsType } from 'antd/lib/table';
import { useTemplateManageContext } from '../contexts/TemplateManageContext';
import { isNullObj } from '@/utils';
import UploadTemplateDialog from './dialogs/UploadTemplateDialog';

const List = () => {
  const {
    templateList,
    typeFilter,
    getTemplateList,
    setSelectKey,
    selectItems,
    deleteTemplateFunc,
    selectAT,
    tplType
  } = useTemplateManageContext();

  const [uploadTemplateVisible, setUploadTemplateVisible] = useState(false);
  // 选中的模板
  const [selectTpl, setSelectTpl] = useState(null);

  // 表格加载
  const [loading, setLoading] = useState(false);
  // 总条目数
  const [total, setTotal] = useState(0);
  // 表格请求参数
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  useEffect(() => {
    const param = { archiveTypeId: selectAT.id, tplType };
    setListQuery((state) => {
      return { ...state, param };
    });
  }, [selectAT, tplType]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param) && selectAT.id) {
      setLoading(true);
      getTemplateList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount || 0);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  // 表格选项相关设置
  const onSelectChange = (selectedKeys: number[]): void => {
    setSelectKey(selectedKeys);
  };

  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };
  /**
   * @description: 展示模板弹窗方法
   */
  const showTemplateDialog = (value: any) => {
    setSelectTpl(value);
    setUploadTemplateVisible(true);
  };

  const delTemplate = (id: number) => {
    deleteTemplateFunc(id);
  };

  const columns: ColumnsType = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center'
    },
    {
      title: '模板名称',
      dataIndex: 'tplName',
      key: 'tplName',
      align: 'center'
    },
    {
      title: '模板类型',
      dataIndex: 'tplType',
      key: 'tplType',
      align: 'center',
      render: (val) => <>{typeFilter(val)}</>
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_text, record: any) => {
        return (
          <Space>
            <Button
              type="link"
              onClick={() => {
                showTemplateDialog(record);
              }}
            >
              编辑
            </Button>
            <Button
              type="text"
              danger
              onClick={() => {
                delTemplate(record.id);
              }}
            >
              删除
            </Button>
          </Space>
        );
      }
    }
  ];

  return (
    <>
      <Table
        columns={columns}
        dataSource={templateList}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          showTotal: (total) => `共 ${total} 条`,
          onChange: pageChange
        }}
        scroll={{
          x: 'max-content'
        }}
        bordered
      />

      {useMemo(
        () => (
          <UploadTemplateDialog
            visible={uploadTemplateVisible}
            data={selectTpl}
            onClose={() => {
              setUploadTemplateVisible(false);
            }}
          />
        ),
        [uploadTemplateVisible]
      )}
    </>
  );
};
export default List;
